export default class AssemblerBase extends cc.Assembler {
    // 普通四边形的属性，根据实际的顶点格式、数量调整

    /** 四边形顶点数量 = 4 */
    protected verticesCount = 4;

    /** 一个四边形按照对角拆分成2个三角形，2*3 = 6个顶点索引 */
    protected indicesCount = 6;

    /** vfmtPosUvColor 结构占5个float32 */
    protected floatsPerVert = 5;

    /** vdata offset info (default = 2) */
    protected uvOffset = 2;

    /** 颜色取值偏移 (default = 4) */
    protected colorOffset = 4;

    protected _renderData: cc.RenderData = null;

    /** 当前节点的所有顶点数据总大小 */
    get verticesFloats() {
        return this.verticesCount * this.floatsPerVert;
    }

    /** 更新颜色 */
    updateColor(comp: any, color: any) {
        let uintVerts = this._renderData.uintVDatas[0];
        if (!uintVerts) return;
        color = color != null ? color : comp.node.color._val;
        let floatsPerVert = this.floatsPerVert;
        let colorOffset = this.colorOffset;
        for (let i = colorOffset, l = uintVerts.length; i < l; i += floatsPerVert) {
            uintVerts[i] = color;
        }
    }

    getVfmt() {
        // to be overwrite
        return null;
    }

    /**
     * 重载getBuffer(), 默认fillBuffers()方法中会调用到
     * @returns 返回一个能容纳自定义顶点数据的buffer
     */
    getBuffer() {
        //@ts-ignore
        return cc.renderer._handle.getBuffer("mesh", this.getVfmt());
    }

    initData() {
        let data = this._renderData;
        data.createQuadData(0, this.verticesFloats, this.indicesCount);
    }

    fillBuffers(comp, renderer) {
        let renderData = this._renderData;
        let vData = renderData.vDatas[0];
        let iData = renderData.iDatas[0];

        let buffer = this.getBuffer();
        let offsetInfo = buffer.request(this.verticesCount, this.indicesCount);

        let vertexOffset = offsetInfo.byteOffset >> 2,
            vbuf = buffer._vData;

        if (vData.length + vertexOffset > vbuf.length) {
            vbuf.set(vData.subarray(0, vbuf.length - vertexOffset), vertexOffset);
        } else {
            vbuf.set(vData, vertexOffset);
        }

        let ibuf = buffer._iData,
            indiceOffset = offsetInfo.indiceOffset,
            vertexId = offsetInfo.vertexOffset;
        for (let i = 0, l = iData.length; i < l; i++) {
            ibuf[indiceOffset++] = vertexId + iData[i];
        }
    }
}